import json
import re

from django import http
from django.conf import settings
from django.contrib.auth import login, authenticate
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection


from AJZF.libs.response_code import RET
from AJZF.utils.fastdfs_conf.fastdfs_storage import FastDFSStorage
from users.models import User
from django.contrib.auth import logout

class Mobile(View):

    def get(self, request, mobile):
        '''
        判断电话是否重复, 返回对应的个数
        :param request:
        :param mobile:
        :return:
        '''
        # 1.从数据库中查询 mobile 对应的个数
        count = User.objects.filter(mobile=mobile).count()

        # 2.拼接参数, 返回
        return http.JsonResponse({'code':0,
                                  'errmsg':'ok',
                                  'count':count})

class RegisterView(View):

    def post(self, request):
        '''接收参数, 保存到数据库'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        sms_code_client = dict.get('phonecode')
        password = dict.get('password')
        password2 = dict.get('password2')


        # 2.校验(整体)
        if not all([mobile,sms_code_client,password, password2]):
            return http.JsonResponse({'code':400,
                                      'errmsg':'缺少必传参数'})
        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'password格式有误'})

        # 5.password2 和 password
        if password != password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入不对'})
        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'mobile格式有误'})

        # 8.sms_code检验 (链接redis数据库)
        redis_conn = get_redis_connection('verify_code')

        # 9.从redis中取值
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 10.判断该值是否存在
        if not sms_code_server:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '短信验证码过期'})
        # 11.把redis中取得值和前端发的值对比
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'code': 400,
                                      'errmsg': '验证码有误'})

        # 12.保存到数据库 (username password mobile)
        try:
            user =  User.objects.create_user(
                                     password=password,
                                     username=mobile,
                                     mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '保存到数据库出错'})

        # 补充: 要实现状态保持:
        login(request, user)

        # 13.拼接json返回
        response = http.JsonResponse({'errno': RET.OK,
                                 'errmsg': "注册成功"})

        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        return response


class LoginView(View):

    def post(self, request):
        '''实现登录接口'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        username = dict.get('mobile')
        password = dict.get('password')


        # 2.校验(整体 + 单个)
        if not all([username, password]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        # 3.验证是否能够登录
        user = authenticate(username=username,
                            password=password)
        # 判断是否为空,如果为空,返回
        if user is None:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '用户名或者密码错误'})

        # 4.状态保持
        login(request, user)

        # 8.返回json
        response = http.JsonResponse({'errno': RET.OK,
                                 'errmsg': '登录成功'})

        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        return response

class Getsession(View):

    def get(self,request):
        user_id = request.user.id
        name = request.user.username
        if not all([user_id,name]):
            return http.JsonResponse({"errno":"4101",
                                      'errmsg':'未登录'})
        return http.JsonResponse({"errno": "0",
                                  'errmsg':'OK',
                                  'data':{"user_id":user_id,"name":name}})


class LogoutView(View):
    """定义退出登录的接口"""

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = http.JsonResponse({'errno': RET.OK, 'errmsg': "用户已退出"})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response



class Photo(View):

    def post(self,request):
        user = request.user
        # img = request.FILES.get('avatar')
        content = request.FILES.get('avatar')
        if not content:
            return http.JsonResponse({'errno': RET.NODATA,
                                          'errmsg': '没有数据'})
        file_id = FastDFSStorage().save(name=None, content=content)
        avatar_url = "http://172.17.0.1:8888/" + file_id
        try:
            User.objects.filter(username=user.username).update(avatar_url=avatar_url)
        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR,
                                      'errmsg': '数据库出错'})
        return http.JsonResponse({"errno": "0",
                                  "errmsg": "OK",
                                  "data": {"name": request.user.username,
                                           "avatar_url": avatar_url,
                                           "mobile": request.user.mobile}
                                  })

        # content = request.FILES.get('avatar')
        # if content is None:
        #     return http.JsonResponse({'errno':RET.PARAMERR,'errmsg':'参数错误'})
        # try:
        #     client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        #     result = client.upload_by_buffer(content.read())
        # except Exception as e:
        #     return http.JsonResponse({'errmsg':"上传失败"})


class UserInfoView(View):
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""

        # 获取界面需要的数据,进行拼接

        username =  request.user.username,
        mobile = request.user.mobile,


        # 返回响应
        return http.JsonResponse({ "errno": "0",
                                   "errmsg": "OK",
                                   "data": {"name": username,
                                            "avatar_url": request.user.avatar_url,
                                            "mobile": mobile } })

    def post(self,request):

        dict = json.loads(request.body.decode())
        name2 = dict.get('name')

        try:
            request.user.username = name2
            request.user.save()
            return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK"})
        except Exception as e:

            return http.JsonResponse({'code': 400,
                                      'errmsg': "参数校验失败/保存数据库失败"})

class Auth(View):

    def get(self,request):

        user = User.objects.get(username=request.user.username)
        real_name = user.real_name
        id_card = user.id_card
        return http.JsonResponse({
            "errno": 0,
            "errmsg": "success",
            "data": {'real_name': real_name, 'id_card': id_card}})

    def post(self,request):
        dict = json.loads(request.body.decode())
        real_name = dict.get('real_name')
        id_card = dict.get('id_card')
        try:
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()
            return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK"})
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': "错误"})

